const UserDB = require('../../db/users_db')
const { signToken } = require('../../util/token')

const errorInfo  = {
    status: 400,
    err: '账号或密码错误'
}

module.exports = async (ctx) =>{

    let { account, password } = ctx.request.body;

    ctx.body = errorInfo
    
    // 短路
    if(!account || !password){ return }

    let users = await UserDB.find({account}, err =>{
         if(err){

            ctx.body = {
                status: 500,
                err: '查询失败' 
            }

            console.error(err)
            
         }
     })
     

    // 短路
    if(!users.length){ return }

    for(let user of users){

        if(user.password === password){

            const { name, age, _id:id } = user

            const token = await signToken({id})

            ctx.cookies.set('token', token, {
                maxAge:  4 * 60 * 60 * 1000
            })

            ctx.body = { name, age , token}
            
            return
        }
    }

}